package com.wyp.didishige.activity.users;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;
import com.wyp.didishige.activity.BaseInfoActivity;
import com.wyp.didishige.activity.ImageBrowserActivity;
import com.wyp.didishige.activity.im.ChatActivity;
import com.wyp.didishige.activity.me.UserEditActivity;
import com.wyp.didishige.adapter.EmoViewPagerAdapter;
import com.wyp.didishige.adapter.UserImageAdapter;
import com.wyp.didishige.db.BlackUser;
import com.wyp.didishige.db.BlackUserManager;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.model.User;
import com.wyp.didishige.utils.CollectionUtils;
import com.wyp.didishige.utils.DateUtil;
import com.wyp.didishige.utils.ImageLoaderUtil;
import com.wyp.didishige.utils.StringUtils;
import com.wyp.didishige.MyApplication;
import com.wyp.didishige.R;
import com.wyp.didishige.activity.dynamic.UserDynamicListActivity;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.wiget.dialog.DialogTips;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 个人资料页面
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
@SuppressLint({"SimpleDateFormat", "ClickableViewAccessibility", "InflateParams"})
public class UserInfoActivity extends BaseInfoActivity implements OnClickListener {

    private static final int EDIT_USER_CODE = 0;
    /**头像区域*/
    private View layout_image;
    /**
     * 会话
     */
    LinearLayout btn_chat;
    /**
     * 关注
     */
    LinearLayout btn_add_friend;
    LinearLayout btn_black;
    /**
     * 相册
     */
    protected ViewPager pager_image;
    /**
     * 兴趣
     */
    protected TextView user_interest;
    /**
     * 签名
     */
    protected TextView user_sign;
    protected TextView publish_community;
    /**
     * 动态数
     */
    protected TextView dynamic_times;
    /**
     * 距离
     */
    protected TextView distance;
    /**
     * 小区、社区
     */
    protected TextView user_community;
    /**
     * 同社区人数
     */
    protected TextView user_community_num;
    /**
     * 楼号
     */
    protected TextView user_build;
    /**
     * 同楼号人数
     */
    protected TextView user_build_num;
    /**
     * 房间号
     */
    protected TextView user_house;
    /**
     * 生活圈
     */
    protected TextView user_lifeCircle;
    /**
     * 同生活圈人数
     */
    protected TextView user_lifeCircle_num;
    /**
     * 工作圈
     */
    protected TextView user_workCircle;
    /**
     * 同工作圈人数
     */
    protected TextView user_workCircle_num;
    /**
     * 家乡
     */
    protected TextView user_hometown;
    /**
     * 同家乡人数
     */
    protected TextView user_hometown_num;
    /**
     * 性别
     */
    protected TextView user_gender;
    protected TextView mBtnAddBlack;
    /**
     * 关注textview
     */
    protected TextView follow_text;

    /**
     * VIP级别
     */
    protected ImageView vip_lv;
    /**
     * 是否同小区
     */
    protected ImageView user_community_star;
    /**
     * 是否同楼
     */
    protected ImageView user_build_star;
    /**
     * 是否同屋
     */
    protected ImageView user_house_star;
    /**
     * 是否同生活圈
     */
    protected ImageView user_lifeCircle_star;
    /**
     * 是否同工作圈
     */
    protected ImageView user_workCircle_star;
    /**
     * 是否老乡
     */
    protected ImageView user_hometown_star;

    /**
     * 当前用户
     */
    protected User user;
    /**
     * 登录
     */
    protected User loginUser;
    /**
     * 动态信息区域
     */
    protected LinearLayout dynamic_lay;
    /**
     * 社区区域
     */
    protected LinearLayout lay_user_community;
    /**
     * 生活圈区域
     */
    protected LinearLayout lay_user_lifeCircle;
    /**
     * 工作圈区域
     */
    protected LinearLayout lay_user_workCircle;
    /**
     * 楼号区域
     */
    protected LinearLayout lay_user_build;
    /**
     * 家乡区域
     */
    protected LinearLayout lay_user_hometown;
    protected LinearLayout lay_bottom;
    /**
     * 头像背景图片
     */
    private ImageView user_bg;

    /**
     * 相册
     */
    protected List<BmobFile> imageList = new ArrayList<BmobFile>();
    /**
     * 相册
     */
    protected ArrayList<String> mPhotos = new ArrayList<String>();
    /**
     * 动态图片
     */
    private ArrayList<BmobFile> dynamicCenterPhotos = new ArrayList<BmobFile>();
    /**
     * 相册图片
     */
    private ArrayList<BmobFile> userPhotos = new ArrayList<BmobFile>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }

        init();
    }

    @Override
    protected void initParamter() {
        super.initParamter();
        loginUser = BmobUser.getCurrentUser(this,User.class);
        userId = getIntent().getStringExtra(Config.KEY_USER_ID);
        if (StringUtils.isNullOrEmpty(userId)) {
            finish();
        }
        user = new User();
        user.setObjectId(userId);
    }

    @Override
    protected void initWidgetListener() {
        super.initWidgetListener();
        btn_add_friend.setOnClickListener(this);
        btn_black.setOnClickListener(this);
        btn_chat.setOnClickListener(this);

        dynamic_lay.setOnClickListener(this);
        lay_user_build.setOnClickListener(goUserListListener);
        lay_user_community.setOnClickListener(goUserListListener);
        lay_user_lifeCircle.setOnClickListener(goUserListListener);
        lay_user_workCircle.setOnClickListener(goUserListListener);
        lay_user_hometown.setOnClickListener(goUserListListener);

        user_community_star.setOnClickListener(starClickListenr);
        user_build_star.setOnClickListener(starClickListenr);
        user_house_star.setOnClickListener(starClickListenr);
        user_lifeCircle_star.setOnClickListener(starClickListenr);
        user_workCircle_star.setOnClickListener(starClickListenr);
        user_hometown_star.setOnClickListener(starClickListenr);

    }

    @Override
    protected void initWidget() {
        layout_image = findViewById(R.id.layout_image);
        user_interest = (TextView) findViewById(R.id.user_interest);
        user_sign = (TextView) findViewById(R.id.user_sign);
        publish_community = (TextView) findViewById(R.id.publish_community);
        distance = (TextView) findViewById(R.id.distance);
        dynamic_times = (TextView) findViewById(R.id.dynamic_times);

        user_community = (TextView) findViewById(R.id.user_community);
        user_community_num = (TextView) findViewById(R.id.user_community_num);
        user_build = (TextView) findViewById(R.id.user_build);
        user_build_num = (TextView) findViewById(R.id.user_build_num);
        user_house = (TextView) findViewById(R.id.user_house);
        user_lifeCircle = (TextView) findViewById(R.id.user_lifeCircle);
        user_lifeCircle_num = (TextView) findViewById(R.id.user_lifeCircle_num);
        user_workCircle = (TextView) findViewById(R.id.user_workCircle);
        user_workCircle_num = (TextView) findViewById(R.id.user_workCircle_num);
        user_hometown = (TextView) findViewById(R.id.user_hometown);
        user_hometown_num = (TextView) findViewById(R.id.user_hometown_num);
        user_gender = (TextView) findViewById(R.id.user_gender);
        follow_text = (TextView) findViewById(R.id.follow_text);
        mBtnAddBlack = (TextView) findViewById(R.id.mBtnAddBlack);

        vip_lv = (ImageView) findViewById(R.id.vip_lv);
        user_community_star = (ImageView) findViewById(R.id.user_community_star);
        user_build_star = (ImageView) findViewById(R.id.user_build_star);
        user_house_star = (ImageView) findViewById(R.id.user_house_star);
        user_lifeCircle_star = (ImageView) findViewById(R.id.user_lifeCircle_star);
        user_workCircle_star = (ImageView) findViewById(R.id.user_workCircle_star);
        user_hometown_star = (ImageView) findViewById(R.id.user_hometown_star);
        user_bg = (ImageView) findViewById(R.id.user_bg);

        dynamic_lay = (LinearLayout) findViewById(R.id.dynamic_lay);
        lay_user_build = (LinearLayout) findViewById(R.id.lay_user_build);
        lay_user_community = (LinearLayout) findViewById(R.id.lay_user_community);
        lay_user_lifeCircle = (LinearLayout) findViewById(R.id.lay_user_lifeCircle);
        lay_user_workCircle = (LinearLayout) findViewById(R.id.lay_user_workCircle);
        lay_user_hometown = (LinearLayout) findViewById(R.id.lay_user_hometown);

        btn_chat = (LinearLayout) findViewById(R.id.btn_chat);
        btn_add_friend = (LinearLayout) findViewById(R.id.btn_add_friend);
        btn_black = (LinearLayout) findViewById(R.id.btn_black);
        lay_bottom = (LinearLayout) findViewById(R.id.lay_bottom);

        pager_image = (ViewPager) findViewById(R.id.pager_image);
    }

    @Override
    protected void initWidgetState() {
        super.initWidgetState();
        if (userId.equals(loginUser.getObjectId())) {
            user_community_star.setVisibility(View.GONE);
            user_build_star.setVisibility(View.GONE);
            user_house_star.setVisibility(View.GONE);
            user_lifeCircle_star.setVisibility(View.GONE);
            user_workCircle_star.setVisibility(View.GONE);
            user_hometown_star.setVisibility(View.GONE);
            lay_bottom.setVisibility(View.GONE);
        }

        initUser();
        getDynamicCount();
    }

    private void getDynamicCount(){
        BmobQuery<Dynamic> dynamicBmobQuery=new BmobQuery<Dynamic>();
        dynamicBmobQuery.addWhereEqualTo("authorId", userId);
        dynamicBmobQuery.findObjects(this, new FindListener<Dynamic>() {
            @Override
            public void onSuccess(List<Dynamic> list) {
                if (list != null && list.size() > 0) {
                    dynamic_times.setText(list.size() + "");
                } else {
                    dynamic_times.setText("暂无动态");
                }
            }

            @Override
            public void onError(int i, String s) {
                dynamic_times.setText("暂无动态");
            }
        });
    }
    /**
     * 获取用户信息
     */
    private void initUser() {
        BmobQuery<User> query = new BmobQuery<User>();
        query.getObject(this, userId, new GetListener<User>() {
            @Override
            public void onSuccess(User us) {
                if (user == null) {
                    finish();
                }
                user = us;
                getUserImage();
                initBottom();
                setUserInfo();
            }

            @Override
            public void onFailure(int i, String s) {
                ShowToast("请检测网络设置");
            }
        });
    }

    /**
     * 初始化底部操作
     */
    private void initBottom() {
        actionBar.setTitle(user.getNick());

        btn_chat.setVisibility(View.VISIBLE);
        btn_chat.setOnClickListener(this);
        boolean isFollow=false;
        if (loginUser.getFollows() != null) {
            for (String objectid : loginUser.getFollows()) {
                if (objectid.equals(userId)){
                    isFollow=true;
                    break;
                }
            }
            if (isFollow){
                btn_chat.setVisibility(View.VISIBLE);
                btn_add_friend.setVisibility(View.GONE);
            }else{
                btn_add_friend.setVisibility(View.VISIBLE);
            }
        }else{
            btn_chat.setVisibility(View.VISIBLE);
            btn_add_friend.setVisibility(View.VISIBLE);
        }

        if (isBlack()){
            mBtnAddBlack.setText(R.string.removeblacklist);
        }else{
            mBtnAddBlack.setText(R.string.addblacklist);

        }
    }

    /***
     * 信息赋值
     */
    @SuppressLint("DefaultLocale")
    private void setUserInfo() {

        setGenderVIP();

        try {
            int meter = (int) DistanceUtil.getDistance(new LatLng(user.getLocation().getLatitude(), user.getLocation().getLongitude()),
                    new LatLng(loginUser.getLocation().getLatitude(),
                            loginUser.getLocation().getLongitude()));
            distance.setText(String.format("%dkm", meter / 1000));
        } catch (Exception e) {
            e.printStackTrace();
            distance.setText("");
        }

        if (user.getUserSign() != null) {
            user_sign.setText(user.getUserSign());
        } else {
        }
        if (user.getCommunity() != null) {
            publish_community.setText(user.getCommunity());
        } else {
        }

        if (user.getCommunity() != null) {
            user_community.setText(user.getCommunity());
        } else {
            user_community.setVisibility(View.GONE);
        }

        if (user.getBuild() != null) {
            user_build.setText(user.getBuild());

        } else {
            user_build.setVisibility(View.GONE);
        }

        if (user.getHouse() != null) {
            user_house.setText(user.getHouse());

        } else {
            user_house.setVisibility(View.GONE);
        }

        if (user.getLifeCircle() != null) {
            user_lifeCircle.setText(user.getLifeCircle());

        } else {
            user_lifeCircle.setVisibility(View.GONE);
        }

        user_interest.setText(user.getUserInterest());

        if (user.getWorkCircle() != null) {
            user_workCircle.setText(user.getWorkCircle());

        } else {
            user_workCircle.setVisibility(View.GONE);
        }

        if (user.getUserHometown() != null) {
            user_hometown.setText(user.getUserHometown());
        } else {
            user_hometown.setVisibility(View.GONE);
        }

        initRelation();
    }

    /**
     * 设置性别、会员级别
     */
    private void setGenderVIP() {
        String age = "";
        if (DateUtil.getAge(user.getUserBirthday()) > 0) {
            age = " " + DateUtil.getAge(user.getUserBirthday()) + "";
        }
        if (user.getSex() != null && user.getSex()) {
            user_gender.setText(String.format("男%s", age));
            user_gender.setBackgroundResource(R.drawable.user_male_bg);
            user_gender.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_user_male), null, null, null);
        } else {
            user_gender.setText(String.format("女%s", age));
            user_gender.setBackgroundResource(R.drawable.user_female_bg);
            user_gender.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_user_famale), null, null, null);
        }

        int level = user.getLevel();
        if (level >= 1 && level < 3) {
            vip_lv.setImageResource(R.drawable.vip_lv_1);
            vip_lv.setVisibility(View.VISIBLE);
        } else if (level >= 3 && level < 6) {
            vip_lv.setImageResource(R.drawable.vip_lv_3);
            vip_lv.setVisibility(View.VISIBLE);

        } else if (level >= 6 && level < 12) {
            vip_lv.setImageResource(R.drawable.vip_lv_6);
            vip_lv.setVisibility(View.VISIBLE);

        } else if (level >= 9) {
            vip_lv.setImageResource(R.drawable.vip_lv_12);
            vip_lv.setVisibility(View.VISIBLE);

        } else {
            vip_lv.setVisibility(View.GONE);
        }
    }

    /**
     * 查询设置小区、楼宇等用户数据
     */
    @SuppressLint("DefaultLocale")
    private void initRelation() {
        if (user.getCommunityUsers() != null && user.getCommunityUsers().size() > 0) {
            user_community_num.setText(String.format("%d人", user.getCommunityUsers().size()));
            user_community_star.setImageResource(R.drawable.ic_user_level);
        } else {
            user_community_star.setImageResource(R.drawable.ic_user_level_empty);
        }
        if (user.getBuildUsers() != null && user.getBuildUsers().size() > 0) {
            user_build_num.setText(String.format("%d人", user.getBuildUsers().size()));
            user_build_star.setImageResource(R.drawable.ic_user_level);
        } else {
            user_build_star.setImageResource(R.drawable.ic_user_level_empty);
        }
        if (user.getHouseUsers() != null && user.getHouseUsers().size() > 0) {
            user_house_star.setImageResource(R.drawable.ic_user_level);
        } else {
            user_house_star.setImageResource(R.drawable.ic_user_level_empty);
        }
        if (user.getLifeCircleUsers() != null && user.getLifeCircleUsers().size() > 0) {
            user_lifeCircle_num.setText(String.format("%d人", user.getLifeCircleUsers().size()));
            user_lifeCircle_star.setImageResource(R.drawable.ic_user_level);
        } else {
            user_lifeCircle_star.setImageResource(R.drawable.ic_user_level_empty);
        }
        if (user.getWorkCircleUsers() != null && user.getWorkCircleUsers().size() > 0) {
            user_workCircle_num.setText(String.format("%d人", user.getWorkCircleUsers().size()));
            user_workCircle_star.setImageResource(R.drawable.ic_user_level);
        } else {
            user_workCircle_star.setImageResource(R.drawable.ic_user_level_empty);
        }
        if (user.getHometownUsers() != null && user.getHometownUsers().size() > 0) {
            user_hometown_num.setText(String.format("%d人", user.getHometownUsers().size()));
            user_hometown_star.setImageResource(R.drawable.ic_user_level);
        } else {
            user_hometown_star.setImageResource(R.drawable.ic_user_level_empty);
        }
    }

    /**
     * 获取用户展示图片
     */
    private void getUserImage() {
        imageList = user.getAvatars();
        if (imageList != null) {
            initImageView();
        }
    }

    int page = 0;

    /**
     * 初始化图片布局
     */
    private void initImageView() {
        List<View> views = new ArrayList<View>();
        int num = 1;
        if (imageList.size() > 8) {
            num = 2;
        }

        for (int i = 0; i < num; ++i) {
            views.add(getGridView(i));
        }

        pager_image.setAdapter(new EmoViewPagerAdapter(views));
        BmobFile file;
        mPhotos.removeAll(mPhotos);
        userPhotos.removeAll(userPhotos);
        for (int i = 0; i < imageList.size(); i++) {
            mPhotos.add(imageList.get(i).getUrl());
            file = new BmobFile();
            file.setUrl(imageList.get(i).getUrl());
            userPhotos.add(file);
        }
        pager_image.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                page = position;
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private View getGridView(final int i) {
        View view = View.inflate(this, R.layout.include_emo_gridview, null);
        GridView gridview = (GridView) view.findViewById(R.id.gridview);
        List<BmobFile> list = new ArrayList<BmobFile>();
        if (i == 0) {
            if (imageList.size() > 8) {
                list.addAll(imageList.subList(0, 8));
            } else {
                list.addAll(imageList);
            }

        } else if (i == 1) {
            list.addAll(imageList.subList(8, imageList.size()));
        }

        final UserImageAdapter gridAdapter = new UserImageAdapter(UserInfoActivity.this,
                list);

        gridview.setAdapter(gridAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                Intent intent = new Intent(UserInfoActivity.this, ImageBrowserActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("photos", userPhotos);
                bundle.putInt("position", position + 8 * page);
                intent.putExtras(bundle);
                startActivity(intent);
                MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_pic_click");
            }
        });
        return view;
    }

    @Override
    public void onClick(View v) {
        Bundle bundle=null;
        switch (v.getId()) {
            case R.id.btn_chat:// 发起聊天
                MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_chat_click");
                bundle = new Bundle();

                BmobIMUserInfo info=new BmobIMUserInfo();
                info.setName(user.getNick());
                info.setAvatar(user.getAvatar());
                info.setUserId(user.getObjectId());

                BmobIMConversation conversation = BmobIM.getInstance().startPrivateConversation(info,false,null);
                bundle.putSerializable(Config.KEY_CONVERSATION, conversation);
                IntentUtil.start_activity(this, ChatActivity.class, bundle);
                finish();
                break;
            case R.id.btn_black:// 黑名单
                showBlackDialog(user.getUsername());
                break;
            case R.id.btn_add_friend://添加好友
                MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_add_click");
                addFollow();
                break;

            case R.id.dynamic_lay://
                MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_dynamic_click");
                bundle = new Bundle();
                bundle.putString(Config.KEY_USER_ID,userId);
                IntentUtil.start_activity(this, UserDynamicListActivity.class,bundle);
                break;
        }
    }

    /**
     * 点击星星事件
     */
    OnClickListener starClickListenr = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.user_hometown_star://家乡
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_like_home_click");
                    if (hasId(user.getHometownUsers(), loginUser.getObjectId())) {
                        user.getHometownUsers().remove(loginUser.getObjectId());
                    } else {
                        user.getHometownUsers().add(loginUser.getObjectId());
                    }
                    break;
                case R.id.user_workCircle_star:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_like_work_click");
                    if (hasId(user.getWorkCircleUsers(), loginUser.getObjectId())) {
                        user.getWorkCircleUsers().remove(loginUser.getObjectId());
                    } else {
                        user.getWorkCircleUsers().add(loginUser.getObjectId());
                    }
                    break;
                case R.id.user_lifeCircle_star:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_like_life_click");
                    if (hasId(user.getLifeCircleUsers(), loginUser.getObjectId())) {
                        user.getLifeCircleUsers().remove(loginUser.getObjectId());
                    } else {
                        user.getLifeCircleUsers().add(loginUser.getObjectId());
                    }
                    break;
                case R.id.user_house_star:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_like_house_click");
                    if (hasId(user.getHouseUsers(), loginUser.getObjectId())) {
                        user.getHouseUsers().remove(loginUser.getObjectId());

                    } else {
                        user.getHouseUsers().add(loginUser.getObjectId());
                    }
                    break;
                case R.id.user_build_star:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_buil_follow_click");
                    if (hasId(user.getBuildUsers(), loginUser.getObjectId())) {
                        user.getBuildUsers().remove(loginUser.getObjectId());

                    } else {
                        user.getBuildUsers().add(loginUser.getObjectId());
                    }
                    break;
                case R.id.user_community_star:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_like_community_click");
                    if (hasId(user.getCommunityUsers(), loginUser.getObjectId())) {
                        user.getCommunityUsers().remove(loginUser.getObjectId());

                    } else {
                        try {
                            user.getCommunityUsers().add(loginUser.getObjectId());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
            }
            initRelation();
            user.update(UserInfoActivity.this);
        }
    };
    /**
     * 查看用户列表
     */
    OnClickListener goUserListListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(Config.KEY_USER, user);
            switch (v.getId()) {
                case R.id.lay_user_hometown:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_home_click");
                    IntentUtil.start_activity(UserInfoActivity.this, HometownUsersActivity.class,bundle);
                    break;
                case R.id.lay_user_workCircle:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_work_click");
                    IntentUtil.start_activity(UserInfoActivity.this, WorkCircleUsersActivity.class, bundle);
                    break;
                case R.id.lay_user_lifeCircle:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_life_click");
                    IntentUtil.start_activity(UserInfoActivity.this, LifeCircleUsersActivity.class, bundle);
                    break;
                case R.id.lay_user_community:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_community_click");
                    IntentUtil.start_activity(UserInfoActivity.this, CommunityUsersActivity.class, bundle);
                    break;
                case R.id.lay_user_build:
                    MobclickAgent.onEvent(UserInfoActivity.this, "userinfo_build_click");
                    IntentUtil.start_activity(UserInfoActivity.this, BuildUsersActivity.class, bundle);
                    break;
            }

        }
    };

    /**
     * 判断列表中是否包含字符串
     *
     * @param userList
     * @param value
     * @return
     */
    private boolean hasId(List<String> userList, String value) {
        if (userList != null && userList.size() > 0) {
            for (String id :
                    userList) {
                if (value.equals(id)) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return false;
    }

    /**
     * 添加好友请求
     */
    private void addFriend() {
//        loading.setTitle("提示");
//        loading.setMessage("努力添加ING");
//        loading.setIndeterminate(false);
//        // 发送tag请求
//        BmobChatManager.getInstance(this).sendTagMessage(BmobConfig.TAG_ADD_CONTACT,
//                user.getObjectId(), new PushListener() {
//
//                    @Override
//                    public void onSuccess() {
//                        // TODO Auto-generated method stub
//                        addFollow();
//                        btn_add_friend.setVisibility(View.GONE);
//                        ShowToast("发送请求成功，等待对方验证！");
//                        loading.cancel();
//                    }
//
//                    @Override
//                    public void onFailure(int arg0, final String arg1) {
//                        // TODO Auto-generated method stub
//                        loading.cancel();
//                        ShowToast("发送失败请重试！");
//                        ShowLog("发送请求失败:" + arg1);
//                    }
//                });
    }

    /**
     * 添加关注
     */
    private void addFollow(){
        loading.setTitle("提示");
        loading.setMessage("努力添加ING");
        loading.setIndeterminate(false);
        if (loginUser.getFollows()==null){
            loginUser.setFollows(new ArrayList<String>());
        }

        if (user.getInvites()==null){
            user.setInvites(new ArrayList<String>());
        }
        Boolean follow = false;
        Boolean invite = false;
        for (int i=0;i<loginUser.getFollows().size();i++){
            if (loginUser.getFollows().get(i).equals(user.getObjectId())){
                follow=true;
                break;
            }
        }

        for (int i=0;i<user.getInvites().size();i++){
            if (user.getInvites().get(i).equals(loginUser.getObjectId())){
                invite=true;
                break;
            }
        }
        if (!follow){
            loginUser.getFollows().add(user.getObjectId());
        }
        if (!invite){
            user.getInvites().add(loginUser.getObjectId());
        }

        loginUser.update(UserInfoActivity.this,new UpdateListener() {
            @Override
            public void onSuccess() {
                btn_add_friend.setVisibility(View.GONE);
            }

            @Override
            public void onFinish() {
                super.onFinish();
                loading.cancel();
            }

            @Override
            public void onFailure(int i, String s) {
                loading.cancel();
            }
        });
    }

    private boolean isBlack(){
        try {
            return BlackUserManager.getInstance(this).getBlackUser(user.getObjectId()) != null;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 显示黑名单提示框
     */
    private void showBlackDialog(final String username) {
        String title="";
        String content="";
        final boolean isBlack = isBlack();
        if (!isBlack){
            title = "加入黑名单";
            content = "加入黑名单，你将不再收到对方的消息，确定要继续吗？";
        }else{
            title = "移除黑名单";
            content = "移除黑名单，你将收到对方的消息，确定要继续吗？";
        }

        DialogTips dialog = new DialogTips(this, title,content, "确定", true, true);
        dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int userId) {
                if (isBlack){
                    BlackUserManager.getInstance(UserInfoActivity.this).deleteBlackUser(BlackUserManager.getInstance(UserInfoActivity.this).getBlackUser(user.getObjectId()));
                    ShowToast("移出黑名单成功");
                    mBtnAddBlack.setText(R.string.addblacklist);
                }else{
                    BlackUser blackUser=new BlackUser();
                    blackUser.setUid(user.getObjectId());
                    blackUser.setName(user.getNick());
                    blackUser.setAvatar(user.getAvatar());
                    BlackUserManager.getInstance(UserInfoActivity.this).insertOrUpdateBlackUser(blackUser);
                    ShowToast("黑名单添加成功!");
                    // 重新设置下内存中保存的好友列表
                    mBtnAddBlack.setText(R.string.removeblacklist);
                }
            }
        });
        // 显示确认对话框
        dialog.show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        if (userId.equals(loginUser.getObjectId())) {
            getMenuInflater().inflate(R.menu.menu_user_center, menu);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }

        if (item.getItemId() == R.id.action_settings) {
            IntentUtil.start_activity_for_result(UserInfoActivity.this, UserEditActivity.class, EDIT_USER_CODE);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case EDIT_USER_CODE:
                    initUser();
                    break;
            }
        }
    }

    @Override
    public void finish() {
        setResult(RESULT_OK);
        super.finish();
    }
}
